const log = require('console').log;

const fs = require('fs');
const path = require('path');

// const http = require('http');
// const https = require('https');

const request = require('request');
const qs = require('qs');

class Getter {

    constructor(options) {
        this.cfg = options;
    }

    splashHtml(url) {
        let options = {
            url,
            timeout: 20,
            wait: 4,
            headers: this.cfg.headers,
        };

        if (this.cfg.proxy) {
            options['proxy'] = this.cfg.proxy;
        }

        const jsCodes = this.cfg.splash_js.filter((item) => {
            return url.indexOf(item.pattern) >= 0;
        });
        if (jsCodes.length > 0) {
            options['js_source'] = jsCodes[0]["js_source"];
        }

        return new Promise((resolve, reject) => {
            // let options = {
            //     url,
            //     timeout: 20,
            //     wait: 4,
            //     headers: { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36' },
            //     'proxy': 'http://localhost:8123',
            //     'js_source': "var ns,i,p,img;ns=document.getElementsByTagName('noscript');for(i=0;i<ns.length;i++){p=ns[i].nextSibling;if(p&&p.className&&p.className.indexOf('lazy-image-placeholder')>-1){img=document.createElement('img');img.setAttribute('src',p.getAttribute('data-src'));img.setAttribute('width',p.getAttribute('data-width'));img.setAttribute('height',p.getAttribute('data-height'));img.setAttribute('alt',p.getAttribute('data-alt'));p.parentNode.replaceChild(img,p);}}"
            // };
            request(`${this.cfg.splashServer}/render.html?${qs.stringify(options)}`, function (error, response, body) {
                if (error) {
                    console.log(error);
                    reject(error);
                    return;
                }
                console.log('code: ' + response.statusCode)
                if (response.statusCode !== 200) {
                    reject("splash response error: " + response.statusCode);
                    return;
                }
                resolve(body);
            })
        })
    }

    downloadAllOfThese(isVerbose, prefix, downloadAddrList, saveAddrList, outputPath) {
        return new Promise((resolve) => {
            let cur = 0;
            const len = downloadAddrList.length;
            const streams = new Array();

            let options = {
                headers: this.cfg.headers,
                timeout: 20000
            };
            if (this.cfg.proxy) {
                options['proxy'] = this.cfg.proxy;
            }

            const r = request.defaults(options)
            for (let i = 0; i < len; i++) {
                // const protocol = downloadAddrList[i].substr(0, 7) === 'http://' ? 'http://' : 'https://';
                // const lib = getLib(protocol);
                streams[i] = fs.createWriteStream(path.join(outputPath, saveAddrList[i]));

                r.get(downloadAddrList[i])
                    .on('response', function (res) {
                        streams[i].on('finish', () => {
                            isVerbose && log(prefix + 'finished - ' + downloadAddrList[i]);
                            streams[i].close();

                            cur++;
                            if (cur === len) resolve();
                        });
                    })
                    .on('error', function (err) {
                        // fs.unlink(path.join(outputPath, saveAddrList[i]));
                        isVerbose && log(prefix + 'error when downloading - ' + downloadAddrList[i] + ' error message: ' + err);

                        cur++;
                        if (cur === len) resolve();
                    })
                    .pipe(streams[i]);


                /*
                            http.get({
                                host: 'localhost',
                                port: '8123',
                                timeout: 2000,
                                path: downloadAddrList[i]
                            }, (res) => {
                                res.pipe(streams[i]);
                
                                streams[i].on('finish', () => {
                                    isVerbose && log(prefix + 'finished - ' + downloadAddrList[i]);
                                    streams[i].close();
                
                                    cur++;
                                    if (cur === len) resolve();
                                });
                            }).on('error', (err) => {
                                // fs.unlink(path.join(outputPath, saveAddrList[i]));
                                isVerbose && log(prefix + 'error when downloading - ' + downloadAddrList[i] + ' error message: ' + err);
                
                                cur++;
                                if (cur === len) resolve();
                            });
                            */
            }
        })
    }

    // getLib(protocol) {
    //     return { 'http://': http, 'https://': https }[protocol];
    // }

}

module.exports = Getter;

// module.exports = {
//     splashHtml,
//     downloadAllOfThese
// }